import cv2
import numpy as np
from apod_object_parser import save_image,get_date

def add_alpha_channel(img):
    b_channel, g_channel, r_channel = cv2.split(img)
    alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255

    img_new = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
    return img_new

def merge_img(jpg_img, png_img, y1, y2, x1, x2):

    if jpg_img.shape[2] == 3:
        jpg_img = add_alpha_channel(jpg_img)
    yy1 = 0
    yy2 = png_img.shape[0]
    xx1 = 0
    xx2 = png_img.shape[1]

    if x1 < 0:
        xx1 = -x1
        x1 = 0
    if y1 < 0:
        yy1 = - y1
        y1 = 0
    if x2 > jpg_img.shape[1]:
        xx2 = png_img.shape[1] - (x2 - jpg_img.shape[1])
        x2 = jpg_img.shape[1]
    if y2 > jpg_img.shape[0]:
        yy2 = png_img.shape[0] - (y2 - jpg_img.shape[0])
        y2 = jpg_img.shape[0]

    alpha_png = png_img[yy1:yy2, xx1:xx2, 3] / 255.0
    alpha_jpg = 1 - alpha_png

    for c in range(0, 3):
        jpg_img[y1:y2, x1:x2, c] = ((alpha_jpg * jpg_img[y1:y2, x1:x2, c]) + (alpha_png * png_img[yy1:yy2, xx1:xx2, c]))

    return jpg_img

#像素化实现

def pixelate_image(image):


    height, width = image.shape[:2]

    #这里的个数决定了像素块的大小
    pixel_size = 1

    new_width = width // pixel_size

    new_height = height // pixel_size

    small_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_LINEAR)

    result_image = cv2.resize(small_image, (width, height), interpolation=cv2.INTER_NEAREST)

    return result_image



def mix(input_path):

    img_png_path = 'starve.png'  # 如果改了导入图片的名字，就改这个

    img_jpg = cv2.imread(input_path, cv2.IMREAD_UNCHANGED)
    img_png2 = cv2.imread(img_png_path, cv2.IMREAD_UNCHANGED)

    #想叠加的那张图片的尺寸
    img_png = cv2.resize(img_png2, (70, 100))
    height, width = img_jpg.shape[:2]

    # 设置叠加位置坐标
    x1 = height//2
    y1 = width//2

    x2 = x1 + img_png.shape[1]
    y2 = y1 + img_png.shape[0]

    res_img = merge_img(img_jpg, img_png, y1, y2, x1, x2)

    #在这里我指定了nasa回传给我们图片的尺寸，因为每天它回传尺寸的不唯一性会导致电脑壁纸无法显示整个图片。
    #可以根据你电脑桌面的尺寸修改这个数值
    new_width = 1000
    new_height = 1000
    resized_img = cv2.resize(res_img, (new_width, new_height))
    # cv2.imshow('Example', resized_img)
    # cv2.waitKey(0)
    resized_img1=pixelate_image(resized_img)
    # print(resized_img1)

    return resized_img1

